import React, {PureComponent} from 'react';
import {connect} from 'react-redux';
import {Button, Card, notification} from 'antd';
import {carrierPriceQuery, clientPriceQuery, getCarrierList, getClientList} from "./actions";
import FilterForm from "../../components/FilterForm";
import moment from "moment";
import {Line} from '@ant-design/plots';
import {getCurrentOrganization, getLastFilter, saveLastFilter} from "../../lib/identity";
import lodash from 'lodash';

const LAST_FILTER = "linePriceAnalysis";

class BusinessAnalysis extends PureComponent {
    componentDidMount() {
        const {dispatch} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        dispatch(clientPriceQuery({...fields, "organizationId": getCurrentOrganization()}));
        dispatch(carrierPriceQuery({...fields, "organizationId": getCurrentOrganization()}));
        dispatch(getClientList());
        dispatch(getCarrierList());
    }

    state = {
        "year": moment().year().toString()
    };

    handleSearch = (values) => {
        const {dispatch} = this.props;
        this.setState({...values});
        saveLastFilter(LAST_FILTER, {...values});
        dispatch(clientPriceQuery({...values, "organizationId": getCurrentOrganization()}));
        dispatch(carrierPriceQuery({...values, "organizationId": getCurrentOrganization()}));
    };

    exportFile = (fileName, fileData) => {
        document.getElementById("fileName").value = fileName;
        if (fileData && fileData.length > 0) {
            const headers = [];
            fileData.forEach(item => {
                for (let key in item) {
                    if (headers.indexOf(key) <= -1) {
                        headers.push(key);
                    }
                }
            });
            document.getElementById("headers").value = lodash.join(headers, ',');
            document.getElementById("rows").value = JSON.stringify(fileData);
            document.getElementById("exportFile").submit();
            notification.success({
                message: '请等待文件导出'
            });
        } else {
            notification.error({
                message: '没有数据可以导出'
            });
        }
    };

    render() {
        const {
            clientPriceCount = [], carrierPriceCount = [], loading, clientList, carrierList
        } = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        const yearList = [];
        yearList.push({'label': '2020', 'value': "2020"});
        yearList.push({'label': '2021', 'value': "2021"});
        yearList.push({'label': '2022', 'value': "2022"});
        yearList.push({'label': '2023', 'value': "2023"});
        yearList.push({'label': '2024', 'value': "2024"});
        yearList.push({'label': '2025', 'value': "2025"});
        yearList.push({'label': '2026', 'value': "2026"});
        // 客户
        const filterSchemaYear = [{
            key: 'year', field: 'year', type: 'listSelector', expandable: true, title: '班列年份', fieldOptions: {
                initialValue: this.state.year || fields.year
            }, controlProps: {
                dataSource: yearList
            }
        },{
            key: 'clientId',
            field: 'clientId',
            type: 'listGroupSelector',
            expandable: true,
            title: '客户',
            fieldOptions: {
                initialValue: this.state.clientId || fields.clientId
            },
            controlProps: {
                dataSource: clientList,
                labelField: "name",
                valueField: "id",
                groupField: "organizationName"
            }
        }];
        // 供应商
        const filterCarrierSchemaYear = [{
            key: 'year', field: 'year', type: 'listSelector', expandable: true, title: '班列年份', fieldOptions: {
                initialValue: this.state.year || fields.year
            }, controlProps: {
                dataSource: yearList
            }
        }, {
            key: 'carrierId',
            field: 'carrierId',
            type: 'listGroupSelector',
            expandable: true,
            title: '供应商',
            fieldOptions: {
                initialValue: this.state.carrierId || fields.carrierId
            },
            controlProps: {
                dataSource: carrierList,
                labelField: "name",
                valueField: "id",
                groupField: "organizationName"
            }
        }];
        const carrierLineData = [];
        carrierPriceCount.forEach(item => {
            carrierLineData.push({"type": item.line, "date": item.month + "月", "value": lodash.round(item.ratio, 2)});
        });
        const clientLineData = [];
        clientPriceCount.forEach(item => {
            clientLineData.push({"type": item.line, "date": item.month + "月", "value": lodash.round(item.ratio, 2)});
        });
        const clientConfig = {
            data: clientLineData, xField: 'date', yField: 'value', yAxis: {
                label: {
                    // 数值格式化为千分位
                    formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
                },
            }, seriesField: 'type', lineStyle: ({type}) => {
                if (type === 'register') {
                    return {
                        lineDash: [4, 4], opacity: 1,
                    };
                }

                return {
                    opacity: 0.5,
                };
            },
        };

        const carrierConfig = {
            data: carrierLineData, xField: 'date', yField: 'value', yAxis: {
                label: {
                    // 数值格式化为千分位
                    formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
                },
            }, seriesField: 'type'
        };

        return (<div>
            <FilterForm schema={filterSchemaYear} callback={this.handleSearch} loading={loading}/>
            <Card title="客户价格分析表" extra={<Button onClick={() => this.exportFile("客户价格分析表", clientLineData)}>导出</Button>}>
                <Line {...clientConfig}/>
            </Card>
            <FilterForm schema={filterCarrierSchemaYear} callback={this.handleSearch} loading={loading}/>
            <Card title="供应商价格分析表" extra={<Button onClick={() => this.exportFile("供应商价格分析表", carrierLineData)}>导出</Button>}>
                <Line {...carrierConfig}/>
            </Card>
            <form
                id="exportFile"
                method="post"
                target="_blank"
                action="/api/orderAnalysis/commonExport"
            >
                <input
                    id="fileName"
                    name="fileName"
                    type="hidden"
                />
                <input
                    id="rows"
                    name="rows"
                    type="hidden"
                />
                <input
                    id="headers"
                    name="headers"
                    type="hidden"
                />
            </form>
        </div>);
    }
}

const mapStateToProps = state => {
    return {
        ...state.linePriceAnalysis
    };
};

export default connect(mapStateToProps)(BusinessAnalysis);
